package com.lesso.yjy.sunflower.infra.repository.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.lesso.yjy.sunflower.domain.repository.EmployeeDeviceRepository;
import com.lesso.yjy.sunflower.infra.assembler.EmployeeDeviceAssembler;
import com.lesso.yjy.sunflower.infra.mapper.EmployeeDeviceMapper;
import com.lesso.yjy.sunflower.model.EmployeeDevice;
import com.lesso.yjy.sunflower.pojo.dto.EmployeeDeviceDTO;
import com.lesso.yjy.sunflower.pojo.dto.EmployeeDeviceQueryDTO;
import com.lesso.yjy.sunflower.pojo.vo.EmployeeDeviceVO;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.List;

@Repository
public class EmployeeDeviceRepositoryImpl implements EmployeeDeviceRepository {
    private final EmployeeDeviceMapper employeeDeviceMapper;

    public EmployeeDeviceRepositoryImpl(EmployeeDeviceMapper employeeDeviceMapper){
        this.employeeDeviceMapper = employeeDeviceMapper;
    }

    @Override
    @Transactional
    public Long save(EmployeeDevice employeeDevice){
        if (employeeDeviceMapper.checkEmployeeExists(employeeDevice.getEmployeeId())<=0){
            throw new RuntimeException("员工不存在");
        }
        if (employeeDeviceMapper.checkDeviceExists(employeeDevice.getDeviceCode())<=0){
            throw new RuntimeException("设备不存在");
        }
        employeeDevice.setDelStatus(0);
        employeeDeviceMapper.insert(employeeDevice);
        return employeeDevice.getId();
    }

    @Override
    public Page<EmployeeDeviceVO> getPageList(EmployeeDeviceQueryDTO dto){
        Page<EmployeeDeviceVO> page = new Page<>(dto.getCurrent(), dto.getSize());
        EntityWrapper<EmployeeDevice> wrapper = new EntityWrapper<>();
        wrapper.eq(EmployeeDevice.EMPLOYEE_ID, dto.getEmployeeId());
        List<EmployeeDevice> employeeDevices = employeeDeviceMapper.selectPage(page, wrapper);
        return page.setRecords(EmployeeDeviceAssembler.INSTANCE.entityListToVOList(employeeDevices));
    }

    @Override
    public Page<EmployeeDeviceVO> getCustomPageList(EmployeeDeviceQueryDTO dto) {
        Page<EmployeeDeviceVO> page = new Page<>(dto.getCurrent(), dto.getSize());
        List<EmployeeDeviceVO> list = employeeDeviceMapper.selectPageList(page, dto);
        return page.setRecords(list);
    }

    @Override
    public void deleteById(Long id){
        employeeDeviceMapper.deleteById(id);
    }

    @Override
    public void updateById(EmployeeDeviceDTO employeeDevice){
        EmployeeDevice entity = EmployeeDeviceAssembler.INSTANCE.dtoToEntity(employeeDevice);
        employeeDeviceMapper.updateById(entity);
    }
}
